package com.chanjiedata.changbs.web.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import com.chanjiedata.changbs.R;
import com.chanjiedata.changbs.base.BaseActivity;
import com.chanjiedata.changbs.base.MainApplication;
import com.chanjiedata.changbs.help.PermissionHelper;
import com.chanjiedata.changbs.help.UserHelper;
import com.chanjiedata.changbs.module.createcard.CreateShopListActivity;
import com.chanjiedata.changbs.module.login.LoginActivity;
import com.chanjiedata.changbs.utlis.ImageUtil;
import com.chanjiedata.changbs.utlis.LogUtil;
import com.chanjiedata.changbs.utlis.SaveViewToImageUtil;
import com.chanjiedata.changbs.utlis.StatusBarUtil;
import com.chanjiedata.changbs.web.inteface.JavaScriptInterface;
import com.chanjiedata.changbs.web.manager.MyChromeClient;
import com.chanjiedata.changbs.web.manager.WebViewClientUtil;

import java.io.File;
import java.lang.ref.WeakReference;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class WebViewActivity extends BaseActivity implements WebViewClientUtil.WebClientLoadListener,
        MyChromeClient.ProgressChangedListener, MyChromeClient.ReceivedTitleListener {


    //全局声明，用于记录选择图片返回的地址值
    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private static final String KEY_WEBURL = "KEY_WEBURL";
    public static final int BACK = 0x1fe;
    public static final int GOTOCARDPRINT = 0x2fe;
    public static final int GOTOCAPTURE = 0x3fe;
    public static final int LOGIN = 0x4fe;

    //文件选择所需
    public final static int FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5 = 2;
    public final static int FILE_CHOOSER_RESULT_CODE = 1;// 表单的结果回调


    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.refresh_tv)
    TextView refreshTv;
    @BindView(R.id.prograssBar)
    ProgressBar prograssBar;
    @BindView(R.id.refreshLayout)
    LinearLayout refreshLayout;
    private MyChromeClient myChromeClient;
    private String url;

    private Handler jsInterfaceHandler = new JsInterfaceHandler(this);


    /**
     * 不带参数的地址
     *
     * @param context
     * @param url
     */
    public static void startActivity(Context context, String url) {
        if (context == null) return;
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(KEY_WEBURL, url);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        MainApplication.addWebActivity(this);
        ButterKnife.bind(this);
        StatusBarUtil.setStatusBarLightMode(this, Color.parseColor("#ffffff"), true);
        initWebView();

    }

    //同步cookie
    private void syncCookie(Context context, String url) {
        try {
            CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeAllCookie();
            cookieManager.setCookie(url, "key=" + UserHelper.getCurrentToken());
            String newCookie = cookieManager.getCookie(url);
            if (newCookie != null) {
                LogUtil.d("Wang", "设置Cookie url=" + url + " ;   cookie=" + newCookie);
            }
        } catch (Exception e) {
            LogUtil.e("Wang: webView.syncCookie failed", e.toString());
        }
    }


    private void initWebView() {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JavaScriptInterface(jsInterfaceHandler), "app");
        webView.setWebViewClient(new WebViewClientUtil(this, this));
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setLoadsImagesAutomatically(true);// 加载网页中的图片
        webView.getSettings().setUseWideViewPort(true); //设置使用视图的宽端口
        webView.getSettings().setAllowFileAccess(true);// 可以读取文件缓存(manifest生效)
        webView.setWebChromeClient(myChromeClient = new MyChromeClient(this, this, this));

        // webView.setDownloadListener(new MyDownloadStart(this));//设置下载监听
        // webview 从Lollipop(5.0)开始webview默认不允许混合模式，https当中不能加载http资源，需要设置开启
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        url = getIntent().getStringExtra(KEY_WEBURL);
        if (!url.contains("http")) {
            url = MainApplication.getServiceHost() + getIntent().getStringExtra(KEY_WEBURL);
        }
//        if (UserHelper.isLogin() &&url.startsWith(BuildConfig.SERVERHEAD)) {
//            syncCookie(this, url);   //同步cookie 地址一定不能为空
//        }
        loadUrl();
    }

    private void loadUrl() {
        String newUrl;
        //统一拼接可
        if (UserHelper.isLogin()) {
            if (url.contains("?")) {
                newUrl = url + "&key=" + UserHelper.getCurrentToken() + "&isBack=true";
            } else {
                newUrl = url + "?key=" + UserHelper.getCurrentToken() + "&isBack=true";
            }
        } else {
            newUrl = url + "&isBack=true";
        }
        webView.loadUrl(newUrl);
        LogUtil.e("wang", "网页请求地址：" + newUrl);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        webView.destroy();
        webView = null;
        MainApplication.removeWebActivity(this);
    }


    public void onResume() {

        super.onResume();

        webView.resumeTimers();

        webView.onResume();

    }

    @Override

    public void onPause() {

        super.onPause();

        webView.onPause();

        webView.pauseTimers();
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
        switch (requestCode) {
            case FILE_CHOOSER_RESULT_CODE:
                if (null == myChromeClient.getmUploadMessage()) {
                    return;
                }
                myChromeClient.getmUploadMessage().onReceiveValue(result);
                myChromeClient.setmUploadMessage(null);
                break;
            case FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5:
                if (null == myChromeClient.getmUploadMessageForAndroid5())
                    return;
                if (result != null) {
                    myChromeClient.getmUploadMessageForAndroid5().onReceiveValue(new Uri[]{result});
                } else {
                    myChromeClient.getmUploadMessageForAndroid5().onReceiveValue(new Uri[]{});
                }
                myChromeClient.setmUploadMessageForAndroid5(null);
                break;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (webView.canGoBack() && event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    int errorCount;

    @Override
    public void loadFinished(String title, boolean isError) {
//        if (isError) {
//            if (errorCount == 2) {
//                refreshLayout.setVisibility(View.VISIBLE);
//                refreshTv.setVisibility(View.VISIBLE);
//                prograssBar.setVisibility(View.GONE);
//                webView.setVisibility(View.GONE);
//                errorCount = 0;
//            } else {
//                errorCount++;
//                loadUrl();
//            }
//        } else {
            refreshLayout.setVisibility(View.GONE);
            prograssBar.setVisibility(View.GONE);
            webView.setVisibility(View.VISIBLE);
//        }
    }


    @OnClick({R.id.refreshLayout})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.refreshLayout:
                webView.loadUrl(url);
                refreshTv.setVisibility(View.GONE);
                prograssBar.setVisibility(View.VISIBLE);
                break;
        }
    }

    /*--------------------------------H5 调用原生--------------------------------*/

    private static class JsInterfaceHandler extends Handler {
        private WeakReference<Activity> weakRefActivity;
        private WebViewActivity context;

        public JsInterfaceHandler(WebViewActivity activity) {
            this.context = activity;
            weakRefActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            Activity activity = weakRefActivity.get();
            if (activity != null) {
                switch (msg.what) {
                    case BACK:
                        activity.finish();
                        break;
                    case LOGIN:
                        UserHelper.loginOut();
                        Intent intent = new Intent(context, LoginActivity.class);
                        context.startActivity(intent);
                        break;
                    case GOTOCAPTURE:
                        captureWebView1(context, context.webView);
                        break;
                    case GOTOCARDPRINT:
                        Intent ShopListIntent = new Intent(context, CreateShopListActivity.class);
                        context.startActivity(ShopListIntent);
                        break;
                }
            }
        }

    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        //进度显示
        if (newProgress > 80) {
            prograssBar.setVisibility(View.GONE);
        } else {
            prograssBar.setProgress(newProgress);
        }
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
        //网页加载完成 这里设置标题
        if (title.contains("http") || title.contains("网页无法打开") || title.contains(".com") || title.contains(".cn")) {
            return;
        }
//        titleTv.setText(title);
    }


    /**
     * 对WebView进行截图
     *
     * @param webView
     * @return
     */
    public static void captureWebView1(Context context, WebView webView) {//可执行
        PermissionHelper.getInstance().getPermission(context, new PermissionHelper.PermissionCallBack() {
            @Override
            public void onSuccess() {
                Bitmap viewBitmap = SaveViewToImageUtil.getViewBitmap(webView);
                String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "畅商服";
                String fileName = System.currentTimeMillis() + ".jpg";
                boolean b = ImageUtil.saveImageToGallery(context, viewBitmap, storePath, fileName);
                if (b) {
                    Toast.makeText(context, "截图保存成功，请在相册查看", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFail() {
                Toast.makeText(context, "获取权限失败", Toast.LENGTH_SHORT).show();
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

}
